package com.example.storage;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import net.sourceforge.pinyin4j.PinyinHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mealhistory.Mealitem;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Fooddatabase extends SQLiteOpenHelper {

    public static final String CREATE_FOOD = "create table food ("
            +"id integer primary key autoincrement,"
            +"foodname ," //unique
            +"img,"
            +"calories,"
            +"unit,"
            +"pinyin text)";

    public static final String CREATE_CATEGORY = "create table category("
            +"id integer primary key autoincrement,"
            +"category_name text,"
            +"category_code integer)";

    public Cursor getSortedData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM food ORDER BY pinyin ASC";
        return db.rawQuery(query, null);
    }
    private Context mContext;

    public Fooddatabase(Context context,String name,SQLiteDatabase.CursorFactory factory,int version){
        super(context,name,factory,version);
        mContext=context;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_FOOD);
        db.execSQL(CREATE_CATEGORY);
        InitDatabase(db);
        Toast.makeText(mContext,"创建成功，请重新进入",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists food");
        db.execSQL("drop table if exists category");
        onCreate(db);
    }

    private void sendRequestWithOkHttp(SQLiteDatabase db,String foodname){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client=new OkHttpClient();
                    Request request=new Request.Builder().url("https://api.oioweb.cn/api/search/FoodHeat?keyword="+foodname+"&page=1").build();
                    Response response=client.newCall(request).execute();
                    String responseData=response.body().string();
                    parseJSONWithJSONObject(responseData,db);
                }
                catch (Exception e){
                    //Log.e("FoodDatabase", "Network request failed", e);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSONWithJSONObject(String jsonData,SQLiteDatabase db){
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONArray results;
            if(jsonObject.has("result")) results = jsonObject.getJSONArray("result");  // 获取名为 "result" 的 JSON 数组
            else return;;
            for (int i = 0; i < results.length(); i++) {
                JSONObject item = results.getJSONObject(i);
                String name = item.optString("name");  // 使用 optString 防止 null 引起程序崩溃
                String img = item.optString("img");
                //String desc = item.optString("desc");
                String heat = item.optString("heat");
                String pinyin = getFullPinyin(name);
                if(name.length()>10||name=="null") continue;
                int calor=extractCalories(heat);
                try {
                    String sql = "INSERT INTO food (foodname, img, calories, unit, pinyin) VALUES ('" + name + "', '" + img + "', " + calor + ", '100', '" + pinyin + "')";
                    db.execSQL(sql);
                    Log.d("We", "Insert successful: foodname " + name + ", img " + img + ", heat " + calor +  ", pinyin " + pinyin);
                } catch (SQLException e) {
                    Log.e("We", "Insert failed: " + e.getMessage());
                    // 处理插入失败的情况，如提示用户、重试逻辑或记录错误等
                }


            }
        }
        catch(Exception e){
            Log.d("Fooddatabase failed","failed",e);
            e.printStackTrace();
        }
    }

    private String getFullPinyin(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
                if (pinyinArray != null) {
                    pinyin.append(pinyinArray[0]);
                }
            } else {
                pinyin.append(c);
            }
        }
        return pinyin.toString().toLowerCase();
    }

    private int extractCalories(String text) {
        //Pattern 类来编译一个正则表达式 \\d+。在Java中，正则表达式 \\d 表示匹配任何数字（0-9），+ 表示匹配前面的子表达式一次或多次。因此，\\d+ 用来匹配一串数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group());
        }
        throw new NumberFormatException("Invalid calorie data: " + text);
    }

    //这个是早午晚使用图片是获得url的方法
    @SuppressLint("Range")
    public String getImageUrlByFoodName(String foodName) {
        SQLiteDatabase db = this.getReadableDatabase();
        String imageUrl = null;
        try {
            String query = "SELECT img FROM food WHERE foodname = ?";
            Cursor cursor = db.rawQuery(query, new String[]{foodName});
            if (cursor.moveToFirst()) {
                imageUrl = cursor.getString(cursor.getColumnIndex("img"));
            }
            cursor.close();
        } catch (Exception e) {
            Log.e("FoodDatabase", "Error getting image URL", e);
        } finally {
            db.close();
        }
        return imageUrl;
    }

    public void InitDatabase(SQLiteDatabase db){
        //String[] foods = {"米饭"};
        String[] foods = {"米饭", "馒头", "面包", "法棍", "玉米", "土豆", "燕麦片", "小米粥", "绿豆粥",
                "百合山药粥", "白棕子", "烧肉粽", "小米杂粮粥", "无糖八宝粥", "南瓜小米粥",
                "荞麦面", "意大利面", "蚕豆", "番茄", "黄瓜", "水煮西兰花", "大白菜", "菠菜",
                "上海青", "清炒娃娃菜", "素炒小白菜", "凉拌木耳", "萝卜", "豆芽", "花菜",
                "清朝油麦菜", "清炒杏鲍菇", "凉拌茄子", "清炒西葫芦", "素炒莴笋", "凉拌海带",
                "油菜", "紫甘蓝", "苹果", "橙子", "橘子", "草莓", "西瓜", "桃子", "火龙果",
                "猕猴桃", "蓝莓", "柚子", "梨", "葡萄", "丑柑", "樱桃"};
        for (String food : foods) {
            sendRequestWithOkHttp(db, food);
        }
    }
}
